<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\teacher\Teacher;

/**
 * 倾诉圈子接口
 */
class Discuss extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected $classList = [];
    protected $reply_ids = [];

    public function _initialize()
    {
        //分类
        $this->classList = model('\app\admin\model\allclass\Allclass')->getClassList();
    }

    /**
     * 倾诉首页列表
     *
     */
    public function index()
    {   
        $data = [];

        $classid = $this->request->request('classid');//分类ID
        $page = $this->request->request('page');//分页
        $pageNum  = 6;//每页个数

        $where = array();
        $where['status'] = 0;
        if(!empty($classid)){
            $where['classid'] = $classid;
        }

        $start = ($page-1)*$pageNum;

        //查询总页数
        $count = db('discuss')->where($where)->order('id', 'desc')->count();
        $maxpages = ceil($count/$pageNum);
        if($page > $maxpages){
            $this->success('最后一页了',$data);
        }

        //帖子
        $discuss_list = db('discuss')->where($where)->order('id', 'desc')->limit($start,$pageNum)->select();
        if(!empty($discuss_list)){
            foreach($discuss_list as $key=>$value){
                $discuss_list[$key]['classid_title'] =model("\app\admin\model\allclass\Allclass")->get_class_name($value['classid']);//分类
                $UserInfo = $this->getUserInfo($value['user_id'],$value['anonymous']);//用户信息
                $discuss_list[$key]['nickname'] = $UserInfo['nickname'];
                $discuss_list[$key]['avatar'] = $UserInfo['avatar'];
                $discuss_list[$key]['gender'] = $UserInfo['gender'];

                $ret = $this->getdiscussfabulous($value['id']);
                $discuss_list[$key]['num_fabulous'] = $ret['num_fabulous'];//点赞数量

                $com_num = $this->getcommentnum($value['id']);//获取评论数量
                $discuss_list[$key]['reply_nums'] = $com_num['nums'];//评论数量

                $discuss_list[$key]['addtime'] = date("Y-m-d H:i:s",$value['createtime']);//创建时间
            }
        }

        //分类列表
        $data = ['maxpages'=>$maxpages,'discuss_list'=>$discuss_list];
        $this->success('请求成功',$data);
    }


    /**
     * 发布
     */
    public function postMessage()
    {
    
        $classid = $this->request->request('classid');//分类ID
        $content = $this->request->request('content');//内容
        $anonymous = $this->request->request('anonymous');//是否匿名
        $user_id = $this->request->request('user_id');//用户ID

        if(empty($user_id)){
            $this->error("请登录后，再发布");
        }

        $content = trim($content);//去除空格
        if(empty($content)){
            $this->error("不能发布空内容");
        }

        //添加
        $data = array();
        $data['classid'] = $classid;
        $data['content'] = $content;
        $data['user_id'] = $user_id;
        $data['anonymous'] = $anonymous;
        $data['status'] = 0;
        $data['createtime'] = time();
       
        $ret = db('discuss')->insertGetId($data);

        if($ret){
            $this->success('发布成功');
        }else{
            $this->success('发布失败');
        }

    }


    /**
     * 评论帖子
     */
    public function comment(){

        $discuss_id = $this->request->request('discuss_id');//帖子ID
        $content = $this->request->request('content');//内容
        $pid = $this->request->request('pid');//回复评论人logID
        $user_id = $this->request->request('user_id');//用户ID
        $type = $this->request->request('type');//回复对象 1回帖 2回复评论人

        if(empty($user_id)){
            $this->error("请登录后，再发布");
        }

        $content = trim($content);//去除空格
        if(empty($content)){
            $this->error("不能发布空内容");
        }

        if($type == 1){

            //添加回帖
            $data = array();
            $data['discuss_id'] = $discuss_id;
            $data['content'] = $content;
            $data['user_id'] = $user_id;
            $data['pid'] = 0;
            $data['type'] = $type;
            $data['status'] = 0;
            $data['createtime'] = time();
            $ret = db('reply_log')->insertGetId($data);

        }else if($type == 2){

            //添加回复评论人
            $data = array();
            $data['discuss_id'] = $discuss_id;
            $data['content'] = $content;
            $data['user_id'] = $user_id;
            $data['pid'] = $pid;
            $data['type'] = $type;
            $data['status'] = 0;
            $data['createtime'] = time();
            $ret = db('reply_log')->insertGetId($data);

        }

        if($ret){
            $this->success('回复成功');
        }else{
            $this->success('回复失败');
        }

    }

    /**
    * 获取帖子用户信息
    */
    public function getUserInfo($user_id = "", $anonymous = 0){
        
        $ret = [];
        if(empty($user_id)){
            return false;
        }

        if($anonymous == 1){
           $nickname = "匿名";
           $avatar = "/uploads/20210329/0de9220466f6ea2f14dde0989cd9fbb0.png";//默认图片
           $gender = 0;
        }else{

            $user_info = db('user')->where('id', $user_id)->find();

            if(empty($user_info['avatar'])){
                $avatar = "/uploads/20210329/0de9220466f6ea2f14dde0989cd9fbb0.png";//默认图片
            }else{
                $avatar = $user_info['avatar'];
            }
            $nickname = $user_info['nickname'];
            $gender = $user_info['gender'];
        }
        $avatar = getImagesUrl($avatar);
        $ret = ['nickname'=>$nickname,'gender'=>$gender,'avatar'=>$avatar];
        return $ret;
    }


    /**
     * 帖子详情
     */

    public function details()
    {
        $discuss_id = $this->request->request('discuss_id');//帖子ID
        $userid = $this->request->request('userid');//用户ID

        if(empty($discuss_id) || empty($userid)){
            $this->error("数据错误");
        }

        //查询帖子详情
        $discuss_info = db('discuss')->where('id', $discuss_id)->find();
        if(empty($discuss_info)){
            $this->error("数据错误");
        }

        $discuss_info['classid_title'] = model("\app\admin\model\allclass\Allclass")->get_class_name($discuss_info['classid']);//分类
        $UserInfo = $this->getUserInfo($discuss_info['user_id'],$discuss_info['anonymous']);//用户信息
        $discuss_info['nickname'] = $UserInfo['nickname'];
        $discuss_info['avatar'] = $UserInfo['avatar'];
        $discuss_info['gender'] = $UserInfo['gender'];

        $ret = $this->getdiscussfabulous($discuss_info['id']);
        $discuss_info['num_fabulous'] = $ret['num_fabulous'];//点赞数量

        /*自己是否点赞*/
        $fabulous = db('discuss_fabulous')->where('user_id', $userid)->where('discuss_id', $discuss_id)->count();
        $article_info['is_fabulous'] = $fabulous;//0没有 1点赞过
        $discuss_info['addtime'] = date("Y-m-d H:i:s",$discuss_info['createtime']);//创建时间

        $data = ['discuss_info'=>$discuss_info];
        $this->success("查询成功",$data);

    }

    /**
     * 获取帖子回复数据
     */
    public function getreplylist(){

        $data = [];
        $discuss_id = $this->request->request('discuss_id');//帖子ID
        $page = $this->request->request('page');//分页
        $pageNum  = 6;//每页个数

        if(empty($discuss_id)){
            $this->error("数据错误");
        }

        if(empty($page)){
            $page = 1;
        }
        
        $start = ($page-1)*$pageNum;

        //查询总页数
        $count = db('reply_log')->where('discuss_id', $discuss_id)->where('type', 1)->count();
        $maxpages = ceil($count/$pageNum);
        if($page > $maxpages){
            $this->success('最后一页了',$data);
        }

        //查询回复帖子
        $reply_list = db('reply_log')->where('discuss_id', $discuss_id)->where('type',1)->order('id', 'desc')->where('status',0)->limit($start,$pageNum)->select();

        if(!empty($reply_list)){
            
            foreach($reply_list as $key=>$value){

                $UserInfo = $this->getUserInfo($value['user_id'],0);//用户信息
                $reply_list[$key]['nickname'] = $UserInfo['nickname'];
                $reply_list[$key]['avatar'] = $UserInfo['avatar'];
                $reply_list[$key]['gender'] = $UserInfo['gender'];
                $reply_list[$key]['addtime'] = date("Y-m-d H:i:s",$value['createtime']);//创建时间
  
                /*查询是否存在评论*/
                $this->reply_ids = [];
                $this->reply_log($value['id']);
                $reply_list[$key]['reply_list'] = $this->reply_log_info($this->reply_ids);
            
            }

        }

        //分类列表
        $data = ['maxpages'=>$maxpages,'reply_list'=>$reply_list];
        $this->success('请求成功',$data);

    }


    /**
     * 组装评论数据
     */
    public function reply_log($id ='')
    {
        $reply_lists = [];
        $reply_lists = db('reply_log')->where('pid', $id)->where('status',0)->select();

        if(!empty($reply_lists)){
            foreach($reply_lists as $key=>$value){
                $this->reply_ids[] = $value['id'];
                $this->reply_log($value['id']);
            }
        }
        return $this->reply_ids;
    }

    /**
     * 组装评论数据详情
     */
    public function reply_log_info($list =array())
    {   
        $data = [];
        if(empty($list)){
            return $data;
        }

        rsort($list,SORT_NUMERIC);

        foreach($list as $key=>$value){

            if($key > 2){
                break;
            }

            $info = db('reply_log')->where('id', $value)->find();
            $TOUserInfo = $this->getUserInfo($info['user_id'],0);//用户信息

            $data[$key]['id'] = $info['id'];
            $data[$key]['content'] = $info['content'];
            $data[$key]['addtime'] =date("Y-m-d H:i:s",$info['createtime']);//创建时间
            $data[$key]['nickname'] = $TOUserInfo['nickname'];

            $p_info = db('reply_log')->where('id', $info['pid'])->find();
            if($p_info['pid'] == 0){
                $data[$key]['name_title'] = "<span>".$TOUserInfo['nickname']."</span>:";
            }else{
                $UserInfo = $this->getUserInfo($p_info['user_id'],0);//用户信息
                $data[$key]['name_title'] = "<span>".$TOUserInfo['nickname']."</span>回复<span>".$UserInfo['nickname']."</span>:";
            }

        }

        return $data;
    }


    /**
     * 更多评论数据组装
     */
    public function morereply_log_info($list =array())
    {   
        $data = [];
        if(empty($list)){
            return $data;
        }

        rsort($list,SORT_NUMERIC);

        foreach($list as $key=>$value){

            if($key > 2){
               
                $info = db('reply_log')->where('id', $value)->find();
                $TOUserInfo = $this->getUserInfo($info['user_id'],0);//用户信息

                $data[$key]['id'] = $info['id'];
                $data[$key]['content'] = $info['content'];
                $data[$key]['addtime'] =date("Y-m-d H:i:s",$info['createtime']);//创建时间

                $p_info = db('reply_log')->where('id', $info['pid'])->find();
                if($p_info['pid'] == 0){
                    $data[$key]['name_title'] = "<span>".$TOUserInfo['nickname']."</span>:";
                }else{
                    $UserInfo = $this->getUserInfo($p_info['user_id'],0);//用户信息
                    $data[$key]['name_title'] = "<span>".$TOUserInfo['nickname']."</span>回复<span>".$UserInfo['nickname']."</span>:";
                }

            }

        }

        return $data;
    }

    /**
     * 获取更多评论 
     * */
    public function getmore(){

        $id = $this->request->request('id');//回复ID

        $this->reply_ids = [];
        $this->reply_log($id);
        $reply_lists = $this->morereply_log_info($this->reply_ids);

        $data = ['reply_lists'=>$reply_lists];
        $this->success('请求成功',$data);
    }



    /**
     * 点赞或取消点赞
     */

    public function getFabulous(){

        $discuss_id = $this->request->request('discuss_id');//帖子ID
        $userid = $this->request->request('userid');//用户ID

        //是否点赞
        $fabulous = db('discuss_fabulous')->where('user_id', $userid)->where('discuss_id', $discuss_id)->count();
        if($fabulous > 0){
            //取消点赞
            db('discuss_fabulous')->where('user_id', $userid)->where('discuss_id', $discuss_id)->delete();
            $msg = "取消成功";
        }else{
            //添加点赞
            $data = ['user_id' => $userid, 'discuss_id' => $discuss_id, 'createtime' => time()];
            db('discuss_fabulous')->insert($data);
            $msg = "点赞成功";
        }

        /**点赞数量*/
        $counts = db('discuss_fabulous')->where('discuss_id', $discuss_id)->count();
        $data = ["counts"=>$counts,"fabulous"=>$fabulous];
        $this->success($msg,$data);

    }


    /**
     * 获取帖子评论数
     */
    public function getcommentnum($id = ""){

        if(empty($id)){
            return ['nums'=>0];
        }

        //评论总数
        $nums = db('reply_log')->where('discuss_id', $id)->count();

        $data = ['nums'=>$nums];
        return $data;

    }


    /**
     * 判断帖子是否被点赞
     */

    public function getdiscussfabulous($id = ""){
        
        if(empty($id)){
            return ['num_fabulous'=>0];
        }

        //点赞
        $num_fabulous = db('discuss_fabulous')->where('discuss_id', $id)->count();

        $data = ['num_fabulous'=>$num_fabulous];
        return $data;

    }
}
